<template>
  <div class="product-list">
    <div class="page-header">
      <div class="header-content">
        <h1>商品管理</h1>
        <p class="subtitle">管理商品信息、库存和状态</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd" class="action-btn">
          <el-icon><Plus /></el-icon>
          新增商品
        </el-button>
        <el-button @click="handleImport" class="action-btn">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-header">
        <el-icon><Search /></el-icon>
        <span>搜索筛选</span>
      </div>
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="商品名称" class="form-item">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入商品名称"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="商品分类" class="form-item">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable class="search-select">
            <el-option label="食品" value="food" />
            <el-option label="饮料" value="drink" />
            <el-option label="生鲜" value="fresh" />
            <el-option label="日用品" value="daily" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" class="form-item">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="search-select">
            <el-option label="在售" value="active" />
            <el-option label="停售" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品表格 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="table-info">
          <span class="info-text">共 {{ filteredProductList.length }} 条商品</span>
          <span v-if="selectedProducts.length > 0" class="selected-info">
            已选择 {{ selectedProducts.length }} 项
          </span>
        </div>
        <div class="table-actions">
          <el-button size="small" :disabled="selectedProducts.length === 0">
            批量操作
          </el-button>
        </div>
      </div>
      
      <div v-if="error" class="error-message">
        <el-icon><Warning /></el-icon>
        <span>{{ error }}</span>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-loading-spinner type="circle" size="large"></el-loading-spinner>
        <p>正在加载商品数据...</p>
      </div>
      
      <el-table 
        v-if="dataLoadSuccess" 
        :data="displayProductList" 
        class="product-table"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center">
          <template #default="scope">
            <span class="index-text">{{ (pagination.current - 1) * pagination.size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="商品ID" width="100" align="center">
          <template #default="scope">
            <span class="product-id">{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="120">
          <template #default="scope">
            <div class="product-name">
              <span class="name-text" :title="scope.row.name">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="batchNo" label="批次号" width="120" align="center">
          <template #default="scope">
            <span class="batch-text">{{ scope.row.batchNo || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)" class="category-tag">
              {{ getCategoryName(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格" width="100" align="center">
          <template #default="scope">
            <span class="spec-text">{{ scope.row.specification || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80" align="center">
          <template #default="scope">
            <span class="unit-text">{{ scope.row.unit || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100" align="center">
          <template #default="scope">
            <span class="price-text">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" align="center">
          <template #default="scope">
            <span class="stock-text" :class="{ 'low-stock': scope.row.stock < 100 }">
              {{ scope.row.stock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="supplier" label="供应商" min-width="120">
          <template #default="scope">
            <span class="supplier-text" :title="scope.row.supplier">{{ scope.row.supplier }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'" class="status-tag">
              {{ scope.row.status === 'active' ? '在售' : '停售' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="110" align="center">
          <template #default="scope">
            <span class="time-text">{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" @click="handleView(scope.row)" class="view-btn">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)" class="edit-btn">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)" class="delete-btn">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredProductList.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
// 所有import必须放在脚本最顶部，这是JavaScript模块规范
import { defineComponent, ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Search, Warning } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'ProductList',
  components: {
    Plus,
    Upload,
    Search,
    Warning
  },
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const selectedProducts = ref([])
    const error = ref('') // 在这里声明error变量
    
    // 搜索表单
    const searchForm = reactive({
      name: '',
      category: '',
      status: ''
    })
    
    // 分页信息
    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })
    
    // 原始商品列表数据
    const originalProductList = ref([
      {
        id: 'P001',
        name: '有机苹果',
        batchNo: 'B20240115001',
        category: 'fresh',
        specification: '500g/袋',
        unit: '袋',
        description: '新鲜有机苹果，无农药残留',
        price: 12.8,
        stock: 150,
        supplier: '绿色农场',
        status: 'active',
        createTime: '2024-01-15'
      },
      {
        id: 'P002',
        name: '纯牛奶',
        batchNo: 'B20240114002',
        category: 'drink',
        specification: '250ml/盒',
        unit: '盒',
        description: '新鲜纯牛奶，营养丰富',
        price: 8.5,
        stock: 200,
        supplier: '乳业公司',
        status: 'active',
        createTime: '2024-01-14'
      },
      {
        id: 'P003',
        name: '面包',
        batchNo: 'B20240113003',
        category: 'food',
        specification: '400g/个',
        unit: '个',
        description: '新鲜烘焙面包，口感松软',
        price: 6.0,
        stock: 80,
        supplier: '面包坊',
        status: 'active',
        createTime: '2024-01-13'
      },
      {
        id: 'P004',
        name: '矿泉水',
        batchNo: 'B20240112004',
        category: 'drink',
        specification: '550ml/瓶',
        unit: '瓶',
        description: '天然矿泉水，富含矿物质',
        price: 2.5,
        stock: 500,
        supplier: '饮料厂',
        status: 'active',
        createTime: '2024-01-12'
      },
      {
        id: 'P005',
        name: '洗发水',
        batchNo: 'B20240111005',
        category: 'daily',
        specification: '750ml/瓶',
        unit: '瓶',
        description: '温和洗发水，适合各种发质',
        price: 25.0,
        stock: 50,
        supplier: '日化厂',
        status: 'inactive',
        createTime: '2024-01-11'
      }
    ])
    
    // 过滤后的商品列表
    const filteredProductList = computed(() => {
      let filtered = originalProductList.value
      
      // 按名称搜索
      if (searchForm.name) {
        filtered = filtered.filter(item => 
          item.name.toLowerCase().includes(searchForm.name.toLowerCase())
        )
      }
      
      // 按分类过滤
      if (searchForm.category) {
        filtered = filtered.filter(item => item.category === searchForm.category)
      }
      
      // 按状态过滤
      if (searchForm.status) {
        filtered = filtered.filter(item => item.status === searchForm.status)
      }
      
      return filtered
    })
    
    // 当前页显示的商品列表
    const displayProductList = computed(() => {
      const start = (pagination.current - 1) * pagination.size
      const end = start + pagination.size
      return filteredProductList.value.slice(start, end)
    })
    
    // 数据加载成功状态
    const dataLoadSuccess = computed(() => {
      return originalProductList.value.length > 0 && !loading.value && !error.value
    })
    
    // 获取分类名称
    const getCategoryName = (category) => {
      const categoryMap = {
        food: '食品',
        drink: '饮料',
        fresh: '生鲜',
        daily: '日用品'
      }
      return categoryMap[category] || category
    }
    
    // 获取分类标签类型
    const getCategoryType = (category) => {
      const typeMap = {
        food: 'success',
        drink: 'primary',
        fresh: 'warning',
        daily: 'info'
      }
      return typeMap[category] || 'info'
    }
    
    // 搜索
    const handleSearch = () => {
      loading.value = true
      // 重置到第一页
      pagination.current = 1
      
      setTimeout(() => {
        try {
          console.log('正在搜索商品数据...')
          console.log(`搜索完成，共 ${filteredProductList.value.length} 条数据`)
          ElMessage.success('搜索完成')
          loading.value = false
        } catch (error) {
          console.error('搜索失败:', error)
          ElMessage.error('搜索失败')
          loading.value = false
        }
      }, 500)
    }
    
    // 重置搜索
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      pagination.current = 1
      handleSearch()
    }
    
    // 新增商品
    const handleAdd = () => {
      router.push('/products/create')
    }
    
    // 批量导入
    const handleImport = () => {
      ElMessage.info('批量导入功能开发中...')
    }
    
    // 查看详情
    const handleView = (row) => {
      router.push(`/products/detail/${row.id}`)
    }
    
    // 编辑商品
    const handleEdit = (row) => {
      router.push(`/products/edit/${row.id}`)
    }
    
    // 删除商品
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除商品 "${row.name}" 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟删除
        const index = originalProductList.value.findIndex(item => item.id === row.id)
        if (index > -1) {
          originalProductList.value.splice(index, 1)
          ElMessage.success('删除成功')
          handleSearch() // 重新加载数据
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    // 表格选择变化
    const handleSelectionChange = (selection) => {
      selectedProducts.value = selection
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1 // 重置到第一页
    }
    
    // 当前页变化
    const handleCurrentChange = (page) => {
      pagination.current = page
    }
    
    // 加载数据
    const loadData = async () => {
      loading.value = true
      error.value = ''
      
      try {
        await new Promise(resolve => setTimeout(resolve, 1000))
        console.log('正在加载商品数据...')
        console.log(`加载完成，共 ${originalProductList.value.length} 条数据`)
        
        // 触发响应式更新
        originalProductList.value = [...originalProductList.value]
        await nextTick()
      } catch (err) {
        console.error('数据加载失败:', err)
        ElMessage.error('数据加载失败')
        error.value = err.message || '未知错误'
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      loadData()
    })
    
    return {
      loading,
      error,
      dataLoadSuccess,
      searchForm,
      pagination,
      originalProductList,
      filteredProductList,
      displayProductList,
      selectedProducts,
      getCategoryName,
      getCategoryType,
      handleSearch,
      handleReset,
      handleAdd,
      handleImport,
      handleView,
      handleEdit,
      handleDelete,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange
    }
  }
})
</script>

<style lang="scss" scoped>
.product-list {
  padding: 8px;
  background-color: #f5f7fa;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0;
  
  .header-content {
    h1 {
      margin: 0 0 2px 0;
      font-size: 20px;
      font-weight: 600;
      color: #1a1a1a;
      line-height: 1.2;
    }
    
    .subtitle {
      margin: 0;
      font-size: 12px;
      color: #666;
      line-height: 1.4;
    }
  }
  
  .header-actions {
    display: flex;
    gap: 6px;
    
    .action-btn {
      height: 32px;
      padding: 0 12px;
      font-weight: 500;
      border-radius: 4px;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }
  }
}

.search-card {
  margin-bottom: 0;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  
  .search-header {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
    
    .el-icon {
      color: #409eff;
      font-size: 14px;
    }
    
    span {
      font-size: 13px;
      font-weight: 500;
      color: #1a1a1a;
    }
  }
  
  .search-form {
    .form-item {
      margin-bottom: 8px;
      margin-right: 16px;
      
      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #333;
        font-size: 12px;
      }
    }
    
    .search-input,
    .search-select {
      width: 160px;
      
      :deep(.el-input__wrapper) {
        border-radius: 4px;
        border: 1px solid #dcdfe6;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: #409eff;
        }
        
        &.is-focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
        }
      }
    }
    
    .search-btn,
    .reset-btn {
      height: 28px;
      padding: 0 12px;
      border-radius: 4px;
      font-weight: 500;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
      }
    }
  }
}

.table-card {
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
    
    .table-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .info-text {
        font-size: 12px;
        color: #666;
      }
      
      .selected-info {
        font-size: 12px;
        color: #409eff;
        font-weight: 500;
      }
    }
    
    .table-actions {
      .el-button {
        border-radius: 3px;
        font-weight: 500;
        font-size: 11px;
      }
    }
  }
  
  .error-message {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 8px;
    margin-bottom: 8px;
    background-color: #fef0f0;
    border: 1px solid #fbc4c4;
    border-radius: 4px;
    color: #f56c6c;
    
    .el-icon {
      font-size: 14px;
    }
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;
    color: #666;
    
    p {
      margin-top: 8px;
      font-size: 12px;
    }
  }
  
  .product-table {
    overflow-x: auto;
    flex: 1;
    
    :deep(.el-table) {
      font-size: 13px;
      width: 100%;
      table-layout: auto;
    }
    
    :deep(.el-table__header) {
      th {
        background-color: #fafafa;
        color: #333;
        font-weight: 600;
        border-bottom: 2px solid #e4e7ed;
        padding: 8px 0;
      }
    }
    
    :deep(.el-table__row) {
      transition: all 0.3s ease;
      
      &:hover {
        background-color: #f5f7fa !important;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
      
      td {
        padding: 8px 0;
      }
    }
    
    .index-text {
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-weight: 500;
      color: #333;
      font-size: 13px;
    }
    
    .product-id {
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-weight: 600;
      color: #409eff;
      background-color: #ecf5ff;
      padding: 3px 6px;
      border-radius: 3px;
      font-size: 12px;
    }
    
    .product-name {
      .name-text {
        font-weight: 500;
        color: #1a1a1a;
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 120px;
        font-size: 13px;
      }
    }
    
    .batch-text {
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-weight: 500;
      color: #909399;
      font-size: 12px;
    }
    
    .category-tag {
      border-radius: 4px;
      font-weight: 500;
      font-size: 12px;
      padding: 3px 6px;
    }
    
    .spec-text {
      font-weight: 500;
      color: #909399;
      font-size: 12px;
    }
    
    .unit-text {
      font-weight: 500;
      color: #909399;
      font-size: 12px;
    }
    
    .price-text {
      font-weight: 600;
      color: #e6a23c;
      font-size: 14px;
    }
    
    .stock-text {
      font-weight: 500;
      color: #67c23a;
      font-size: 13px;
      
      &.low-stock {
        color: #f56c6c;
        font-weight: 600;
      }
    }
    
    .supplier-text {
      color: #606266;
      font-size: 13px;
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 120px;
    }
    
    .status-tag {
      border-radius: 4px;
      font-weight: 500;
      font-size: 12px;
      padding: 3px 6px;
    }
    
    .time-text {
      color: #909399;
      font-size: 12px;
    }
    
    .action-buttons {
      display: flex;
      gap: 4px;
      justify-content: center;
      
      .view-btn,
      .edit-btn,
      .delete-btn {
        border-radius: 3px;
        font-weight: 500;
        font-size: 12px;
        padding: 4px 8px;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }
      }
      
      .view-btn {
        border-color: #dcdfe6;
        color: #606266;
        
        &:hover {
          border-color: #409eff;
          color: #409eff;
        }
      }
      
      .edit-btn {
        background-color: #409eff;
        border-color: #409eff;
        
        &:hover {
          background-color: #66b1ff;
          border-color: #66b1ff;
        }
      }
      
      .delete-btn {
        background-color: #f56c6c;
        border-color: #f56c6c;
        
        &:hover {
          background-color: #f78989;
          border-color: #f78989;
        }
      }
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
    padding-top: 8px;
    border-top: 1px solid #f0f0f0;
    
    .pagination {
      :deep(.el-pagination__total) {
        font-weight: 500;
        color: #666;
        font-size: 12px;
      }
      
      :deep(.el-pagination__sizes) {
        .el-select {
          .el-input__wrapper {
            border-radius: 3px;
          }
        }
      }
      
      :deep(.btn-prev),
      :deep(.btn-next) {
        border-radius: 3px;
        transition: all 0.3s ease;
        
        &:hover {
          background-color: #409eff;
          color: white;
        }
      }
      
      :deep(.el-pager) {
        li {
          border-radius: 3px;
          transition: all 0.3s ease;
          
          &:hover {
            background-color: #409eff;
            color: white;
          }
          
          &.active {
            background-color: #409eff;
            color: white;
          }
        }
      }
      
      :deep(.el-pagination__jump) {
        .el-input__wrapper {
          border-radius: 3px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .product-list {
    padding: 6px;
    gap: 6px;
  }
  
  .search-form {
    .form-item {
      margin-right: 12px;
      
      .search-input,
      .search-select {
        width: 140px;
      }
    }
  }
}

@media (max-width: 768px) {
  .product-list {
    padding: 4px;
    gap: 4px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    
    .header-content {
      h1 {
        font-size: 18px;
      }
    }
    
    .header-actions {
      width: 100%;
      justify-content: flex-start;
    }
  }
  
  .search-form {
    .form-item {
      margin-right: 6px;
      margin-bottom: 6px;
      
      .search-input,
      .search-select {
        width: 100px;
      }
    }
  }
  
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
    
    .table-actions {
      width: 100%;
      justify-content: flex-start;
    }
  }
  
  .product-table {
    overflow-x: auto;
    
    :deep(.el-table) {
      font-size: 12px;
      width: 100%;
      table-layout: auto;
    }
    
    :deep(.el-table__row) {
      td {
        padding: 6px 0;
      }
    }
    
    .action-buttons {
      flex-direction: column;
      gap: 2px;
      
      .view-btn,
      .edit-btn,
      .delete-btn {
        width: 100%;
        padding: 3px 6px;
        font-size: 11px;
      }
    }
  }
  
  .pagination-container {
    justify-content: center;
    
    .pagination {
      :deep(.el-pagination__jump) {
        display: none;
      }
    }
  }
}

@media (max-width: 480px) {
  .product-list {
    padding: 2px;
    gap: 2px;
  }
  
  .search-form {
    .form-item {
      width: 100%;
      margin-right: 0;
      
      .search-input,
      .search-select {
        width: 100%;
      }
    }
  }
  
  .product-table {
    :deep(.el-table) {
      font-size: 11px;
      
      .el-table__cell {
        padding: 4px 2px;
      }
    }
    
    .action-buttons {
      .view-btn,
      .edit-btn,
      .delete-btn {
        font-size: 10px;
        padding: 2px 4px;
      }
    }
  }
}
</style>